﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using TLib.Xna;

namespace COMP477_Scorchery
{
    class Arrow : GameObject
    {
        public Vector3 Velocity;
        public Vector3 Direction;
        public Vector3 Forces;
        public float Weight;

        public float HangTime;

        private Vector3 Gravity = new Vector3(0, -9.8f, 0);
        private float SpinSpeed = 15;

        public Arrow(Model model)
            : base(model)
        {
            Velocity = new Vector3(0, 0, 0);
            Direction = new Vector3(0, 0, 0);

            Weight = 1;

            HangTime = 0;
        }

        public void Update(GameTime gameTime, Vector3 force)
        {
            float delta = (float)gameTime.ElapsedGameTime.TotalSeconds;

            if (Velocity.Length() != 0)
            {
                //Apply gravity
                ApplyForce(delta, Gravity * Weight);

                //Apply external forces
                ApplyForce(delta, force);
            }

            Position += Velocity * delta;

            if (PositionY <= 0)
            {
                PositionY = 0.5f;
                Velocity = Vector3.Zero;
            }

            if (Velocity.Length() != 0)
            {
                if (Yaw % (Math.PI * 2) >= Math.PI || (Yaw % (Math.PI * 2) >= -Math.PI && Yaw % (Math.PI * 2) < 0))
                    Pitch = -(float)Math.Atan2((double)Velocity.X, (double)Velocity.Y) - (float)(Math.PI / 2);
                else
                    Pitch = (float)Math.Atan2((double)Velocity.X, (double)Velocity.Y) - (float)(Math.PI / 2);
                Roll += delta * SpinSpeed;
            }

            if (Velocity != Vector3.Zero && PositionY > 0)
                HangTime += (Velocity.X + Velocity.Z) * delta;
        }

        private void ApplyForce(float delta, Vector3 force)
        {
            Velocity += force * delta;
        }
    }
}
